#include "stdafx.h"
#include "AdapterCtrl.h"


CAdapterCtrl::CAdapterCtrl(void)
	: m_nAmount(0)
	, m_nIndex(0)
{
	m_pAddresses = NULL;
	m_pCurrAddresses = NULL;
	m_pAdapter = NULL;
	//Init();
}


CAdapterCtrl::~CAdapterCtrl(void)
{
}

void CAdapterCtrl::Init(void)
{
	ULONG outBufLen = 0;
	DWORD dwRetVal = 0;
	m_nAmount = 0;
    m_pAddresses = (IP_ADAPTER_ADDRESSES*) malloc(sizeof(IP_ADAPTER_ADDRESSES));

    // Make an initial call to GetAdaptersAddresses to get the 
    // size needed into the outBufLen variable
    if (GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_GATEWAYS, NULL, m_pAddresses, &outBufLen) 
        == ERROR_BUFFER_OVERFLOW) {
            free(m_pAddresses);
            m_pAddresses = (IP_ADAPTER_ADDRESSES*) malloc(outBufLen);
    }


    // Make a second call to GetAdapters Addresses to get the
    // actual data we want
    if ((dwRetVal = GetAdaptersAddresses(AF_INET, 
        GAA_FLAG_INCLUDE_GATEWAYS, 
        NULL, 
        m_pAddresses, 
        &outBufLen)) == NO_ERROR) {
            // If successful, output some information from the data we received
           PIP_ADAPTER_ADDRESSES pCurrAddresses = m_pAddresses;
			while(pCurrAddresses)
			{
				m_nAmount++;
				pCurrAddresses = pCurrAddresses->Next;
			}
			m_pCurrAddresses = m_pAddresses;
}




	PIP_ADAPTER_INFO pAdapterInfo;

/* variables used to print DHCP time info */

    ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
    pAdapterInfo = (IP_ADAPTER_INFO *) malloc(sizeof (IP_ADAPTER_INFO));
    if (pAdapterInfo == NULL) {
        printf("Error allocating memory needed to call GetAdaptersinfo\n");
        return ;
    }
// Make an initial call to GetAdaptersInfo to get
// the necessary size into the ulOutBufLen variable
    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        free(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) malloc(ulOutBufLen);
        if (pAdapterInfo == NULL) {
            printf("Error allocating memory needed to call GetAdaptersinfo\n");
            return ;
        }
    }
	if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR)
        m_pAdapter = pAdapterInfo;

}


CString CAdapterCtrl::GetMACAddr()
{
	CString szMAC;
	 if (m_pCurrAddresses->PhysicalAddressLength != 0) {
		 szMAC.Format(_T("%02X-%02X-%02X-%02X-%02X-%02X"),
			 m_pCurrAddresses->PhysicalAddress[0],
			 m_pCurrAddresses->PhysicalAddress[1],
			 m_pCurrAddresses->PhysicalAddress[2],
			 m_pCurrAddresses->PhysicalAddress[3],
			 m_pCurrAddresses->PhysicalAddress[4],
			 m_pCurrAddresses->PhysicalAddress[5]);
	 }
	return szMAC;
}


int CAdapterCtrl::SetCurAdapIndex(int nIndex)
{
	if(nIndex > m_nAmount)return GetLastError();
	m_nIndex = nIndex;
	PIP_ADAPTER_ADDRESSES pCurrAddresses = m_pAddresses;
	int i = 0;
	while (pCurrAddresses != NULL)
	{
		
		
		if (i == nIndex)
		{
			break;
		}
		i++;
		pCurrAddresses = pCurrAddresses->Next;
	}
	m_pCurrAddresses = pCurrAddresses;
	return 0;
}


CString CAdapterCtrl::GetAdapterName(void)
{
	return CString(m_pCurrAddresses->Description);
}


CString CAdapterCtrl::GetIPAddr(void)
{
	TCHAR str[200];
	DWORD leng=200;
	WSAAddressToString(m_pCurrAddresses->FirstUnicastAddress->Address.lpSockaddr,
		m_pCurrAddresses->FirstUnicastAddress->Length,
		NULL,
		str,
		&leng);
	return CString(str);
}


CString CAdapterCtrl::GetMaskAddr(void)
{
	CString str;
	PIP_ADAPTER_INFO pAdapter;
	pAdapter = m_pAdapter;

		for (int i = 0; i < m_nIndex; i++)
		{
			pAdapter = pAdapter->Next;
		}

		if(pAdapter)
		{
		str = pAdapter->IpAddressList.IpMask.String;
		}
		else
		{
			str = _T("");
		}

	return str;
}



CString CAdapterCtrl::GetGateWay(void)
{

	
	if(m_pCurrAddresses->FirstGatewayAddress == NULL)
		return NULL;
	TCHAR str[200];
	DWORD leng=200;
	WSAAddressToString(m_pCurrAddresses->FirstGatewayAddress->Address.lpSockaddr,
		m_pCurrAddresses->FirstGatewayAddress->Length,
		NULL,
		str,
		&leng);
	return CString(str);

	/*

	PIP_ADAPTER_INFO pAdapterInfo;
    PIP_ADAPTER_INFO pAdapter = NULL;
    DWORD dwRetVal = 0;
    UINT i;

//variables used to print DHCP time info
    struct tm newtime;
    char buffer[32];
    errno_t error;

    ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);
    pAdapterInfo = (IP_ADAPTER_INFO *) malloc(sizeof (IP_ADAPTER_INFO));
    if (pAdapterInfo == NULL) {
        printf("Error allocating memory needed to call GetAdaptersinfo\n");
        return _T("");
    }
// Make an initial call to GetAdaptersInfo to get
// the necessary size into the ulOutBufLen variable
    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        free(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) malloc(ulOutBufLen);
        if (pAdapterInfo == NULL) {
            printf("Error allocating memory needed to call GetAdaptersinfo\n");
            return _T("");
        }
    }
	*/
/*
	CString str;
	 PIP_ADAPTER_INFO pAdapter;
	 pAdapter = m_pAdapter;

		for (int i = 0; i < m_nIndex; i++)
		{
			pAdapter = pAdapter->Next;
		}

		if(pAdapter)
		{
		str = pAdapter->GatewayList.IpAddress.String;
		}
		else
		{
			str = _T("");
		}

	return str;
	*/
}


CString CAdapterCtrl::GetDNSAddrs(void)
{

	if(m_pCurrAddresses->FirstDnsServerAddress == NULL)
		return NULL;
	TCHAR str[200];
	DWORD leng=200;
	CString szDNS = _T("");
	CString temp = _T("");
	PIP_ADAPTER_DNS_SERVER_ADDRESS pDNS = m_pCurrAddresses->FirstDnsServerAddress;
	while (pDNS)
	{
		WSAAddressToString(pDNS->Address.lpSockaddr,
			pDNS->Address.iSockaddrLength,
			NULL,
			str,
			&leng);
		pDNS = pDNS->Next;
		if(pDNS)
		{
			temp.Format(_T("%s\r\n"),str);
		}
		else
		{
			temp = str;
		}
		szDNS += temp;
		
	}

	return szDNS;
}


int CAdapterCtrl::GetAdapNum(void)
{

	return m_nAmount;
}


CString CAdapterCtrl::GetPCName(void)
{
	/*
	FIXED_INFO FinxedInfo;
	DWORD dwBuffSize=0;
	GetNetworkParams(&FinxedInfo, &dwBuffSize);
	GetNetworkParams(&FinxedInfo, &dwBuffSize);
	CString szHostName;
	
	szHostName.Format(_T("%s"), (TCHAR)FinxedInfo.HostName);
	szHostName = _T("asd");
	return szHostName;
	*/
	
	
	/*FIXED_INFO *pFixedInfo;
    ULONG ulOutBufLen;
    pFixedInfo = (FIXED_INFO *) malloc(sizeof (FIXED_INFO));

    ulOutBufLen = sizeof (FIXED_INFO);

	GetNetworkParams(pFixedInfo, &ulOutBufLen);
	pFixedInfo = (FIXED_INFO *) malloc(ulOutBufLen);
	GetNetworkParams(pFixedInfo, &ulOutBufLen);
	CString szHostName;
	szHostName = pFixedInfo->HostName;
	free(pFixedInfo);
	return szHostName;
	*/

	char cHostName[256];
	gethostname(cHostName,256);
	return CString(cHostName);

}



int CAdapterCtrl::SetDNS(CString szDNSAddr)
{
	szDNSAddr.Replace(_T("\r\n"), _T(" "));
	HKEY hKey;
	CString szKeyName = _T("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\");
	szKeyName += m_pCurrAddresses->AdapterName;
	szKeyName += _T("\\");
	//LPCTSTR strTemp = szKeyName.GetBuffer(szKeyName.GetLength());
	if ( RegOpenKeyEx(HKEY_LOCAL_MACHINE,
		szKeyName,
		NULL,
		KEY_ALL_ACCESS,
		&hKey) != ERROR_SUCCESS )
	{
	return GetLastError();
	}

	/*TCHAR cDNSAddr[256];
	_tcscpy_s(cDNSAddr, szDNSAddr);
	cDNSAddr = szDNSAddr.GetBuffer(256);*/
	RegSetValueEx(hKey,
		_T("DhcpNameServer"),
		NULL,
		REG_SZ,
		(BYTE*)szDNSAddr.GetBuffer(),
		szDNSAddr.GetAllocLength()*2);
	szDNSAddr.ReleaseBuffer();
	RegCloseKey(hKey);
	return 0;
}


bool CAdapterCtrl::NotifyIPChange(CString lpszAdapterName, int nIndex, CString pIPAddress, CString pNetMask)
{
	typedef int (CALLBACK* DHCPNOTIFYPROC)(LPWSTR, LPWSTR, BOOL, DWORD, DWORD, DWORD, int);
	BOOL			bResult = FALSE;
	HINSTANCE		hDhcpDll;
	DHCPNOTIFYPROC	pDhcpNotifyProc;
	
	//MultiByteToWideChar(CP_ACP, 0, lpszAdapterName, -1, wcAdapterName,256);

	if( ( hDhcpDll = LoadLibrary(_T("dhcpcsvc") ) ) == NULL)
		return FALSE;

	//_tcscpy_s(asd, lpszAdapterName.operator LPCWSTR);
	if((pDhcpNotifyProc = (DHCPNOTIFYPROC)GetProcAddress(hDhcpDll, "DhcpNotifyConfigChange")) != NULL)
		if((pDhcpNotifyProc)(NULL,
			lpszAdapterName.GetBuffer(),
			TRUE,
			nIndex,
			inet_addr((char*)pIPAddress.GetBuffer()),
			inet_addr((char*)pNetMask.GetBuffer()),
			0) == ERROR_SUCCESS)
			bResult = TRUE;

	FreeLibrary(hDhcpDll);
	return TRUE;
}


bool CAdapterCtrl::RegSetAdapter(CString szAdapterName, CString szIPAddress, CString szNetMask, CString szNetGate)
{

	HKEY hKey;
	CString szKeyName = _T("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\");
	szKeyName += m_pCurrAddresses->AdapterName;
	if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
				szKeyName,
				NULL,
				KEY_WRITE,
				&hKey) != ERROR_SUCCESS)
		return FALSE;
	

	
	RegSetValueEx(hKey, _T("IPAddress"), 0, REG_SZ, (BYTE*)szIPAddress.GetBuffer(), szIPAddress.GetLength()*2);
	RegSetValueEx(hKey, _T("SubnetMask"), 0, REG_SZ,(BYTE*)szNetMask.GetBuffer(), szNetMask.GetLength()*2);
	RegSetValueEx(hKey, _T("DefaultGateway"), 0, REG_MULTI_SZ, (BYTE*)szNetGate.GetBuffer(), szNetGate.GetLength()*2);

	RegCloseKey(hKey);

	return TRUE;
	return false;
}


void CAdapterCtrl::Release(void)
{
	 if(m_pAddresses != NULL) free(m_pAddresses);
	 if(m_pAdapter != NULL) free(m_pAdapter);
}
